package world.criver.h50909.tool;

import org.springframework.stereotype.Component;
import world.criver.h50909.data.daSqlite;
import world.criver.h50909.entity.*;

import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.time.chrono.ChronoLocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;
@Component
public class toolEquipmentState {
    /**
     * 查询此刻报警的设备
     * @return
     */
    public List<entEquipmentInfo> queryAlarms(){
        long t=System.currentTimeMillis();
        daSqlite.lock.lock();
        List<entEquipmentInfo> as= daSqlite.tool.query("select a.* from equipment_info a join equipment_state as b on a.name=b.name where "+t+"-b.timestamp<5000 and b.alarmState=1",entEquipmentInfo.class);
        daSqlite.lock.unlock();
        return as;
    }
    /**
     * 查询单台设备某时间段的每一天的运行情况
     * @param name 设备名
     * @param start_date 开始日期
     * @param end_date 终止日期
     * @return
     */
    public List<entEquipmentDayTotal> queryEquipmentTotal(String name, LocalDate start_date, LocalDate end_date){
        long ds=ChronoUnit.DAYS.between(start_date,end_date);
        ArrayList<entEquipmentDayTotal> das=new ArrayList<>();
        daSqlite.lock.lock();
        for(int i=0;i< ds;i++){
            String as=""+start_date.getYear()+(start_date.getMonthValue()>9?"":"0")+start_date.getMonthValue()+(start_date.getDayOfMonth()>9?"":"0")+start_date.getDayOfMonth();
            long a=start_date.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();
            int d=start_date.getDayOfMonth();
            start_date=start_date.plusDays(1);
            long b=start_date.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();
            //统计待机时长
            List<entLong> all=daSqlite.tool.query("select count(*) as num from equipment_state where timestamp>="+a+" and timestamp<"+b+" and awaitState=1 and name='"+name+"'", entLong.class);
            long aa=0,bb=0;
            if(!all.isEmpty())aa=all.get(0).getNum();
            try {
                all = daSqlite.tool.query("select awaitTime as num from equipment_state_old where name='" + name + "' and `date`='" + as + "'", entLong.class);
                if (!all.isEmpty()) aa += all.get(0).getNum();
            }catch (Exception e){}
            //统计加工时长
            all=daSqlite.tool.query("select count(*) as num from equipment_state where timestamp>="+a+" and timestamp<"+b+" and processState=1 and name='"+name+"'", entLong.class);
            if(!all.isEmpty())bb=all.get(0).getNum();
            try {
                all = daSqlite.tool.query("select processTime as num from equipment_state_old where name='" + name + "' and `date`='" + as + "'", entLong.class);
                if (!all.isEmpty()) bb += all.get(0).getNum();
            }catch (Exception e){}
            das.add(new entEquipmentDayTotal(d,aa*5,bb*5));
        }
        daSqlite.lock.unlock();
        return das;
    }

    /**
     * 查询所有设备指定时间段内的每日统计
     * @param start_date
     * @param end_date
     * @return
     */
    public List<entEquipmentDayTotal> queryAllEquipmentTotal(LocalDate start_date, LocalDate end_date){
        long ds= ChronoUnit.DAYS.between(start_date,end_date);
        ArrayList<entEquipmentDayTotal> das=new ArrayList<>();
        daSqlite.lock.lock();
        for(int i=0;i< ds;i++){
            String as=""+start_date.getYear()+(start_date.getMonthValue()>9?"":"0")+start_date.getMonthValue()+(start_date.getDayOfMonth()>9?"":"0")+start_date.getDayOfMonth();
            long a=start_date.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();
            int d=start_date.getDayOfMonth();
            start_date=start_date.plusDays(1);
            long b=start_date.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();
            long aa=0,bb=0;
            //统计待机时长
            List<entLong> all=daSqlite.tool.query("select count(*) as num from equipment_state where timestamp>="+a+" and timestamp<"+b+" and awaitState=1", entLong.class);
            if(!all.isEmpty())aa=all.get(0).getNum();
            try {
                all = daSqlite.tool.query("select sum(awaitTime) as num from equipment_state_old where `date`='" + as + "'", entLong.class);
                if (!all.isEmpty()) aa += all.get(0).getNum();
            }catch (Exception e){}
            //统计加工时长
            all=daSqlite.tool.query("select count(*) as num from equipment_state where timestamp>="+a+" and timestamp<"+b+" and processState=1", entLong.class);
            if(!all.isEmpty())bb=all.get(0).getNum();
            try {
                all = daSqlite.tool.query("select sum(processTime) as num from equipment_state_old where `date`='" + as + "'", entLong.class);
                if (!all.isEmpty()) bb += all.get(0).getNum();
            }catch (Exception e){}
            das.add(new entEquipmentDayTotal(d,aa*5,bb*5));
        }
        daSqlite.lock.unlock();
        return das;
    }

    /**
     * 添加状态
     * @param info
     */
    public void add(entEquipmentState info){
        daSqlite.lock.lock();
        daSqlite.tool.update("insert into equipment_state values ('"+info.getName()+"',"+info.getTimestamp()+","
                +info.getAlarmState()+","+info.getProcessState()+","+info.getAwaitState()+",'"+info.getProgram()+"','"+info.getSpeed()+"')");
        daSqlite.lock.unlock();
    }

    /**
     * 获取最新程序名
     * @param name
     * @return
     */
    public String getProgram(String name){
        long t=System.currentTimeMillis()-5000;
        daSqlite.lock.lock();
        List<String> as=daSqlite.tool.query("select program from equipment_state where timestamp>"+t+" limit 1", String.class);
        daSqlite.lock.unlock();
        if(as.isEmpty())return "";
        return as.get(0);
    }
    /**
     * 获取最新速度
     * @param name
     * @return
     */
    public String getSpeed(String name){
        long t=System.currentTimeMillis()-5000;
        daSqlite.lock.lock();
        List<String> as=daSqlite.tool.query("select speed from equipment_state where timestamp>"+t+" limit 1", String.class);
        daSqlite.lock.unlock();
        if(as.isEmpty())return "";
        return as.get(0);
    }

    /**
     * 最新状态
     * @param name
     * @return
     */
    public entEquipmentState state(String name){
        long t=System.currentTimeMillis()-5000;
        daSqlite.lock.lock();
        List<entEquipmentState> as=daSqlite.tool.query("select * from equipment_state where name='"+name+"' and timestamp>"+t+" limit 1", entEquipmentState.class);
        daSqlite.lock.unlock();
        if(as.isEmpty())return new entEquipmentState();
        return as.get(0);
    }

    /**
     * 保存昨日数据
     * @param name
     */
    public void saveYesterdayData(String name,LocalDate now){
        LocalDate yesterday=now.plusDays(-1);
        long yesterday_t=yesterday.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();
        long now_t=now.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();
        daSqlite.lock.lock();
        //查询state中昨日的数据
        long await=0,process=0;
        List<entLong> qw=daSqlite.tool.query("select count(*) as num from equipment_state where name='"+name+"' and timestamp>="+yesterday_t+" and timestamp<"+now_t+" and awaitState=1",entLong.class);
        if(!qw.isEmpty())await=qw.get(0).getNum();
        qw=daSqlite.tool.query("select count(*) as num from equipment_state where name='"+name+"' and timestamp>="+yesterday_t+" and timestamp<"+now_t+" and processState=1",entLong.class);
        if(!qw.isEmpty())process=qw.get(0).getNum();
        //查询昨日数据是否保存
        String y=""+yesterday.getYear()+(yesterday.getMonthValue()>9?"":"0")+yesterday.getMonthValue()+(yesterday.getDayOfMonth()>9?"":"0")+yesterday.getDayOfMonth();
        qw=daSqlite.tool.query("select count(*) as num from equipment_state_old where name='"+name+"' and `date`='"+y+"'",entLong.class);
        if(qw.isEmpty() || qw.get(0).getNum()==0){
            daSqlite.tool.update("insert into equipment_state_old values ('"+name+"','"+y+"',"+await+","+process+")");
        }else{
            daSqlite.tool.update("update equipment_state_old set awaitTime=awaitTime+"+await+",processTime=processTime+"+process+" where name='"+name+"' and `date`='"+y+"'");
        }
        //清空state中昨日数据
        daSqlite.tool.update("delete from equipment_state where name='"+name+"' and timestamp>="+yesterday_t+" and timestamp<"+now_t);
        daSqlite.lock.unlock();
    }
}
